process.env.NODE_ENV = 'production'

const webpack = require('webpack')
const configFactory = require('../webpack.config')
const chalk = require('chalk')
const formatWebpackMessages = require('./formatWebpackMessages')
const { normalizationArgv } = require('./utils/normalization')
const argv = require('minimist')(process.argv.slice(2))

const { app } = normalizationArgv(argv)
console.log(chalk.greenBright(`编译应用: ${app}`))

// 环境变量处理
require('./utils/env').genEnv(app)

// 获取编译包时 根据参数获取
const config = configFactory({ env: 'production', name: app })
const compile = webpack(config)

compile.run((err, stats) => {
  let messages;
  if (err) {
    if (!err.message) {
      throw err;
    }

    let errMessage = err.message;

    if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
      errMessage +=
        '\nCompileError: Begins at CSS selector ' +
        err['postcssNode'].selector;
    }

    messages = formatWebpackMessages({
      errors: [errMessage],
      warnings: [],
    });
  } else {
    messages = formatWebpackMessages(
      stats.toJson({ all: false, warnings: true, errors: true })
    );
  }

  // 构建模块输出
  console.log(stats.toString({ colors: true }))

  if (messages.errors.length) {
    // Only keep the first error. Others are often indicative
    // of the same problem, but confuse the reader with noise.
    if (messages.errors.length > 1) {
      messages.errors.length = 1;
    }
    throw new Error(messages.errors.join('\n\n'));
  }
  if (
    process.env.CI &&
    (typeof process.env.CI !== 'string' ||
      process.env.CI.toLowerCase() !== 'false') &&
    messages.warnings.length
  ) {
    // Ignore sourcemap warnings in CI builds. See #8227 for more info.
    const filteredWarnings = messages.warnings.filter(
      w => !/Failed to parse source map/.test(w)
    );
    if (filteredWarnings.length) {
      console.log(
        chalk.yellow(
          '\nTreating warnings as errors because process.env.CI = true.\n' +
          'Most CI servers set it automatically.\n'
        )
      );
      throw new Error(filteredWarnings.join('\n\n'));
    }
  }

  const warnings = messages.warnings

  if (warnings.length) {
    console.log(chalk.yellow('Compiled with warnings.\n'));
    console.log(warnings.join('\n\n'));
    console.log(
      '\nSearch for the ' +
      chalk.underline(chalk.yellow('keywords')) +
      ' to learn more about each warning.'
    );
    console.log(
      'To ignore, add ' +
      chalk.cyan('// eslint-disable-next-line') +
      ' to the line before.\n'
    );
  } else {
    console.log(chalk.green('Compiled successfully.\n'));
  }
})